﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Text;
using Telerik.Sitefinity.Web.UI.ControlDesign;
using Newtonsoft.Json;
using Sitefinity.Contrib.SocialWidgets.Shared;
using System.Collections;

namespace Sitefinity.Contrib.SocialWidgets.YouTube
{
    [ControlDesigner(typeof(YouTubeVideoRotatorWidgetDesigner)), PropertyEditorTitle("YouTube Video Rotator")]
    public partial class YouTubeVideoRotatorWidget : System.Web.UI.UserControl
	{
        const string FEED_URL = "http://gdata.youtube.com/feeds/base/users/{0}/uploads?alt=rss";
        const int BUTTON_WIDTH = 24;

        public string UserName { get; set; }
        public int MaximumVideos { get; set; }
        public int RotationTimerSeconds { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }

		/// <summary>
		/// Handles the Load event of the Page control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		protected void Page_Load(object sender, EventArgs e)
		{
            // ensure the username is valid
            if (string.IsNullOrEmpty(UserName)) return;
            
            var sb = new StringBuilder();

            try
            {
                // retrieve contents
                var url = string.Format(FEED_URL, UserName);
                var vidXml = XDocument.Load(url);
                if (vidXml == null) return;

                // parse to collection
                var videos = from t in vidXml.Descendants("item") select new { href = t.Element("link").Value, alt = t.Element("title").Value, src = ToThumbnail(t.Element("link").Value) };

                string prefix = string.Format("youtube_{0}", HttpUtility.HtmlAttributeEncode(UserName));
                ImageRotatorUtility imageRotatorUtility = new ImageRotatorUtility(prefix);
                imageRotatorUtility.AddReferences(this.Page);

                string jsonVideos = JsonConvert.SerializeObject(videos);
                string script = imageRotatorUtility.GenerateScript(jsonVideos, RotationTimerSeconds * 1000);
                Page.ClientScript.RegisterStartupScript(this.GetType(), prefix, script);

                var first = videos.First();
                string html = imageRotatorUtility.GenerateHtml(Width, Height, first.href, first.src, first.alt);
                sb.Append(html);
            }
            catch
            {
                sb.Append("YouTube Image Query failed.");
            }

            
            YouTubeVideoRotatorHtml.Text = sb.ToString();
		}

        /// <summary>
        /// Retrieves a thumbnail for a youtube video link
        /// </summary>
        /// <param name="input">The url to the video.</param>
        /// <returns></returns>
        protected string ToThumbnail(string input)
        {
            // retrieve url
            var uri = new Uri(input);

            // parse to querystring
            var qs = HttpUtility.ParseQueryString(uri.Query);
            var vidID = qs["v"];

            // create thumbnail from qs
            return string.IsNullOrEmpty(vidID) ? string.Empty : string.Format("http://img.youtube.com/vi/{0}/0.jpg", vidID);
        }
	}
}